package com.pt25.base.model.monitor.sql;


import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

@Order(4)
@Aspect
@Component
@Slf4j
public class SqlPerformanceAspect {

    private final static Long SQL_TIME_THRESHOLD = 100L;

    @Around("@annotation(com.pt25.base.model.monitor.sql.SqlPerformance)")
    public Object logPerformance(ProceedingJoinPoint pjp) throws Throwable {
        long startTime = System.currentTimeMillis();
        String name = "-";
        String result = "y";
        try {
            name = pjp.getSignature().toShortString();
            return pjp.proceed();
        } catch (Throwable t) {
            result = "n";
            throw t;
        } finally {
            long endTime = System.currentTimeMillis();
            long time = endTime - startTime;
            if (time < SQL_TIME_THRESHOLD) {
                log.info("name={},result={},time={}", name, result, time);
            } else {
                log.error("name={},result={},time={}", name, result, time);
            }
        }
    }
}
